# -*- coding:utf-8 -*-
import os
from pathlib import Path

def SaveExtensionFile(tableName, rowContentList, exportExtension):
    """
    保存为Extension文件
    """
    # 组织导出保存目录
    exportDirectoryPath = _get_export_directory_path(tableName, exportExtension)
    # 判断目录是否存在,不存在创建目录
    if os.path.exists(exportDirectoryPath) == False:
        os.mkdir(exportDirectoryPath)
    # 生成文件名和文件路径
    fileName = _get_file_english_name(tableName) + "." + exportExtension
    savePath = _combine_path(exportDirectoryPath, fileName)
    # 创建并写入文件
    f = open(savePath, 'w')
    f.write(rowContentList)
    # 刷io缓存
    f.flush()
    f.close()

def _get_file_english_name(fileName:str):
    """
    只输出英文和字符作为文件名
    """
    index = 0
    for i in range(len(fileName)):
        if fileName[i].isalpha():
            index = i
            break
    if index > 0:
        fileName = fileName[0:index]
    return "F_" + fileName

def _combine_path(path1, path2):
    """
    并两个路径字符串,本函数不会因为path2以目录分隔符开头就认为是绝对路径,然后直接返回path2
    """
    # path1 不是以 / 分隔符结尾 追加分隔符
    path1 = Path(path1)
    # path 如果是以 / 分隔符开头,去掉分隔符
    path2 = Path(path2)
    # path1 + path2 
    return Path.joinpath(path1, path2)


def _get_export_directory_path(tableName, exportRootPath):
    """
    获取导出某种生成文件的存储目录
    """ 
    # 获取表格相对于Excel文件夹的相对路径
    cur_path = os.path.dirname(os.path.realpath(__file__))
    relativeUri = os.path.join(cur_path, self.CONFIG_FILE_NAME)
    
    # 注意:Uri转为的字符串中会将中文转义为%xx,需要恢复为非转义形式
    return Path.GetDirectoryName(_combine_path(exportRootPath, Uri.UnescapeDataString(relativeUri.ToString())))



def get_excel_column_name(columnNumber):
    """
    获取Excel中的列编号对应的名称
    说明:
        将Excel中的列编号转为列名称(第1列为A,第28列为AB)
        return 返回字符串
    """
    result = ""
    temp = columnNumber
    quotient = 0
    remainder = 0
    while True:
        quotient = temp / 26
        remainder = temp % 26
        if remainder == 0:
            remainder = 26
            quotient -= quotient
        # 转数字计算后,再转为字符 和 result 组成字符串
        result = chr(ord('A') + remainder - 1) + result
        temp = quotient
        if quotient <= 0:
            return result
